package github.aloofcoder.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import github.aloofcoder.common.utils.PageUtils;
import github.aloofcoder.common.utils.Query;
import github.aloofcoder.gulimall.product.dao.CategoryDao;
import github.aloofcoder.gulimall.product.entity.CategoryEntity;
import github.aloofcoder.gulimall.product.service.CategoryBrandRelationService;
import github.aloofcoder.gulimall.product.service.CategoryService;
import github.aloofcoder.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    /**
     * 本地缓存
     */
//    private Map<String, Object> cache = new HashMap<>();

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedissonClient redisson;

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 查出所有分类
        List<CategoryEntity> list = this.list();
        List<CategoryEntity> level1Menus = list.stream().filter(item -> item.getParentCid() == 0).map(item -> {
            item.setChildren(getChildrens(item, list));
            return item;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());

        // 组装父子的树行结构
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> categoryIds) {
        // TODO - 检查当前删除的菜单是否被别的地方引用
        baseMapper.deleteBatchIds(categoryIds);
    }

    @Override
    public Long[] findCategoryPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = getParentCid(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        // 通过分类-品牌关联表分类数据
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        // TODO - 修改其他关联数据
    }

    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {

        /**
         * 1. 空结果缓存：缓存穿透
         * 2. 设置过期时间，添加随机值，解决缓存雪崩
         * 3. 加锁
         */
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");

        if (StringUtils.isEmpty(catalogJSON)) {
            System.out.println("缓存不命中。。。查询数据库。。。。");
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedissonLock();
            return catalogJsonFromDb;
        }
        System.out.println("缓存命中。。。直接返回。。。");
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        RLock lock = redisson.getLock("product-categorys-lock");
        lock.lock(30, TimeUnit.SECONDS);
        Map<String, List<Catelog2Vo>> catalogFromDb;
        try {
            catalogFromDb = getCatalogFromDb();
        } finally {
            lock.unlock();
        }

        return catalogFromDb;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {

        String token = UUID.randomUUID().toString();
        //  redis 获取分布式锁，    // 设置过期时间
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", token, 300, TimeUnit.SECONDS);
        if (lock) {
            System.out.println("获取分布式锁成功。。。");
//            // 设置过期时间
//            redisTemplate.expire("lock", 30, TimeUnit.SECONDS);
            // 加锁成功
            Map<String, List<Catelog2Vo>> catalogFromDb;
            try {
                 catalogFromDb = getCatalogFromDb();
            } finally {
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                //TODO - 锁的自动续期
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), token);
            }
            // 必须原子操作使用lua脚本解锁
//            String lockValue = redisTemplate.opsForValue().get("lock");
//            if (token.equalsIgnoreCase(lockValue)) {
//                redisTemplate.delete("lock");
//            }
            return catalogFromDb;
        } else {
            System.out.println("获取分布式锁失败，等待重试。。。");
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 加锁失败，进行重试(自旋方式)
            return getCatalogJsonFromDbWithRedisLock();
        }
    }

    private Map<String, List<Catelog2Vo>> getCatalogFromDb() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }
        System.out.println("查询了数据库......." + Thread.currentThread());

        List<CategoryEntity> entities = this.baseMapper.selectList(null);

        List<CategoryEntity> level1Categorys = getParent_cid(entities, 0L);

        Map<String, List<Catelog2Vo>> map = level1Categorys.stream()
                .collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {

                    // 二级分类列表
                    List<CategoryEntity> categoryEntities = getParent_cid(entities, v.getCatId());

                    List<Catelog2Vo> level2Catelogs = null;

                    if (Objects.nonNull(categoryEntities)) {
                        level2Catelogs = categoryEntities.stream().map(level2 -> {
                            Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, level2.getCatId().toString(), level2.getName());

                            // 查询三级分类
                            List<CategoryEntity> level3Catalog = getParent_cid(entities, level2.getCatId());

                            if (Objects.nonNull(level3Catalog)) {

                                List<Catelog2Vo.Catalog3Vo> catalog3Vos = level3Catalog.stream().map(level3 -> {
                                    Catelog2Vo.Catalog3Vo catalog3Vo = new Catelog2Vo.Catalog3Vo(level2.getCatId().toString(), level3.getCatId().toString(), level3.getName());
                                    return catalog3Vo;
                                }).collect(Collectors.toList());

                                catelog2Vo.setCatalog3List(catalog3Vos);
                            }
                            return catelog2Vo;
                        }).collect(Collectors.toList());
                    }

                    return level2Catelogs;
                }));

        String catalogStr = JSON.toJSONString(map);
        redisTemplate.opsForValue().set("catalogJSON", catalogStr, 1, TimeUnit.DAYS);
        return map;
    }

    /**
     * 从数据查询并封装分类
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithLocalLock() {

//        Map<String, List<Catelog2Vo>> catalogJson = (Map<String, List<Catelog2Vo>>) cache.get("catalogJson");
//        if (Objects.isNull(catalogJson)) {
//            调用业务
//            cache.put("catalogJson", map);
//        }
//        return catalogJson;

        synchronized (this) {
            // 得到锁以后需要再缓存中再确认一次
            String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
            if (!StringUtils.isEmpty(catalogJSON)) {
                Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
                });
                return result;
            }
            System.out.println("查询了数据库......." + Thread.currentThread());
            /**
             * 将数据库的多次查询变为一次
             */
            List<CategoryEntity> entities = this.baseMapper.selectList(null);


            List<CategoryEntity> level1Categorys = getParent_cid(entities, 0L);

            Map<String, List<Catelog2Vo>> map = level1Categorys.stream()
                    .collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {

                        // 二级分类列表
                        List<CategoryEntity> categoryEntities = getParent_cid(entities, v.getCatId());

                        List<Catelog2Vo> level2Catelogs = null;

                        if (Objects.nonNull(categoryEntities)) {
                            level2Catelogs = categoryEntities.stream().map(level2 -> {
                                Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, level2.getCatId().toString(), level2.getName());

                                // 查询三级分类
                                List<CategoryEntity> level3Catalog = getParent_cid(entities, level2.getCatId());

                                if (Objects.nonNull(level3Catalog)) {

                                    List<Catelog2Vo.Catalog3Vo> catalog3Vos = level3Catalog.stream().map(level3 -> {
                                        Catelog2Vo.Catalog3Vo catalog3Vo = new Catelog2Vo.Catalog3Vo(level2.getCatId().toString(), level3.getCatId().toString(), level3.getName());
                                        return catalog3Vo;
                                    }).collect(Collectors.toList());

                                    catelog2Vo.setCatalog3List(catalog3Vos);
                                }
                                return catelog2Vo;
                            }).collect(Collectors.toList());
                        }

                        return level2Catelogs;
                    }));

            String catalogStr = JSON.toJSONString(map);
            redisTemplate.opsForValue().set("catalogJSON", catalogStr, 1, TimeUnit.DAYS);
            return map;
        }
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> categoryEntities, Long parent_cid) {
        List<CategoryEntity> entities = categoryEntities.stream().filter(item ->
                item.getParentCid().equals(parent_cid)
        ).collect(Collectors.toList());

        return entities;
    }

    private List<Long> getParentCid(Long catelogId, List<Long> paths) {
        CategoryEntity categoryEntity = this.getById(catelogId);
        paths.add(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            getParentCid(categoryEntity.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 递归查找所有菜单的子菜单
     *
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        return all.stream().filter(item -> item.getParentCid().equals(root.getCatId()))
                .map(item -> {
                    item.setChildren(getChildrens(item, all));
                    return item;
                })
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
    }
}
